package com.sx.medicinecard.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

@Slf4j
public class HttpUtils {


    public static String doPost(JSONObject entity, String url) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //headers.set("Cookie","uid=CgoUFGVOQLon52oCFy1YAg==");
        // 创建 RestTemplate 对象
        RestTemplate restTemplate = new RestTemplate();

        // 创建 HTTP 实体对象
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(entity, headers);
        log.info("发送post请求，请求路径：" + url);
        log.info("发送post请求，请求体：" + requestEntity);
        // 发送 POST 请求到外部接口
        ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, requestEntity, String.class);
        String body = response.getBody();
        log.info("接收到请求返回，返回体：" + body);
        return body;
    }

    public static ResponseEntity<String> doPostEntityWithTimeout(JSONObject jsonObject, String url, int timeout) throws TimeoutException {
        // 设置带有超时配置的 HTTP 客户端
        HttpClient client = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build())
                .build();

        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON));
        log.info("发送post请求，请求路径：" + url);
        log.info("发送post请求，请求体：" + post.getEntity().toString());
        try {
            HttpResponse response = client.execute(post);
            // 处理响应
            String responseBody = EntityUtils.toString(response.getEntity());
            log.info("接收到请求返回，返回体：" + responseBody);
            return new ResponseEntity<>(responseBody, HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
        } catch (SocketTimeoutException e) {
            throw new TimeoutException("请求超时，超时设置为 " + timeout + " 毫秒");
        } catch (IOException e) {
            throw new RuntimeException("HTTP 请求出错", e);
        }
    }


    public static String doPut(JSONObject entity, String url) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //headers.set("Cookie","uid=CgoUFGVOQLon52oCFy1YAg==");
        // 创建 RestTemplate 对象
        RestTemplate restTemplate = new RestTemplate();

        // 创建 HTTP 实体对象
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(entity, headers);
        log.info("发送post请求，请求路径：" + url);
        log.info("发送post请求，请求体：" + requestEntity);
        // 发送 POST 请求到外部接口
        ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.PUT, requestEntity, String.class);
        String body = response.getBody();
        log.info("接收到请求返回，返回体：" + body);
        return body;
    }

    public static String doPostWithToken(JSONObject entity, String url,String token) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        //headers.setContentType("application/json");
        headers.set("Content-Type","application/json");
        headers.set("Authorization","Bearer "+token);
        //headers.set("Cookie","uid=CgoUFGVOQLon52oCFy1YAg==");
        // 创建 RestTemplate 对象
        RestTemplate restTemplate = new RestTemplate();

        // 创建 HTTP 实体对象
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(entity, headers);
        log.info("发送post请求，请求路径：" + url);
        log.info("发送post请求，请求体：" + requestEntity);
        // 发送 POST 请求到外部接口
        ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, requestEntity, String.class);
        String body = response.getBody();
        log.info("接收到请求返回，返回体：" + body);
        return body;
    }
    public static String doHeyePost(JSONObject entity, String url) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Cookie", "uid=CgoUFGVOQLon52oCFy1YAg==");
        // 创建 RestTemplate 对象
        RestTemplate restTemplate = new RestTemplate();

        // 创建 HTTP 实体对象
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(entity, headers);

        log.info("发送post请求，请求体：" + requestEntity);
        // 发送 POST 请求到外部接口
        ResponseEntity<String> response = restTemplate.exchange(
                url, HttpMethod.POST, requestEntity, String.class);
        String body = response.getBody();
        log.info("接收到请求返回，返回体：" + body);
        return body;
    }
    public static String doPostEntityJSON(String url, Object postReq) {
        RequestConfig requestCong = RequestConfig.custom().setConnectionRequestTimeout(5000)
                .setConnectTimeout(5000).setSocketTimeout(5000).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestCong);
        httpPost.setEntity(new StringEntity(JSON.toJSONString(postReq), ContentType.APPLICATION_JSON));

        CloseableHttpClient httpClient = HttpClients.custom().setMaxConnTotal(100).setMaxConnPerRoute(100).setRetryHandler(
                new DefaultHttpRequestRetryHandler(0, false)).disableAutomaticRetries().build();

        Integer code = null;
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpPost);
            //code = httpResponse.getStatusLine().getStatusCode();

            String ret = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
            return ret;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 发送get请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String doGet(String url) throws IOException {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建HttpGet请求并设置URL
            HttpGet request = new HttpGet(url);
            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(request);
            try {
                // 从响应中获取状态码、头部信息等
                String statusCode = String.valueOf(response.getStatusLine().getStatusCode());
                return statusCode;
                // 如果需要获取响应内容，则通过EntityUtils工具类将其转换为字符串或者进行其他处理
//                org.apache.http.HttpEntity entity = response.getEntity();
//                if (entity != null) {
//                    return EntityUtils.toString(entity);
//                } else {
//                    return null;
//                }
            } finally {
                // 关闭响应
                response.close();
            }
        } finally {
            // 关闭HttpClient连接池
            httpClient.close();
        }
    }
}
